package com.yong.common.net;

import com.yong.common.net.configs.Constant;
import com.yong.common.net.util.RxUtils;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @Description: Retrofit 封装工具类
 * @Author: yong
 * @time 2020/7/6 10:04
 * @Version: 1.0
 */
public class RetrofitUtil {
    private static RetrofitUtil retrofitUtil;
    private static Retrofit retrofit;

    /**
     * 当前url
     */
    private String url;

    public static RetrofitUtil getInstance() {
        if (retrofitUtil == null) {
            synchronized (RetrofitUtil.class) {
                if (retrofitUtil == null) {
                    retrofitUtil = new RetrofitUtil();
                }
            }
        }
        return retrofitUtil;
    }

    private synchronized Retrofit getRetrofit(String url) {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .addInterceptor(interceptor)
                .addInterceptor(new ReadCookiesInterceptor())
                .addInterceptor(new SaveCookiesInterceptor())
                .sslSocketFactory(RxUtils.createSSLSocketFactory(), new RxUtils.TrustAllManager())
                .build();

        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(url)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .client(okHttpClient)
                    .build();
        }
        return retrofit;
    }

    public <T> T getApiService(Class<T> cl) {
        if (url == null) {
            url = Constant.BASE_URL;
            retrofit = getRetrofit(url);
            //当url手动更改后
        } else if (!url.equals(Constant.BASE_URL)) {
            url = Constant.BASE_URL;
            retrofit = null;
            retrofit = getRetrofit(url);
        }

        return retrofit.create(cl);
    }

}
